package com.qcby.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class AdminInterceptor implements HandlerInterceptor{

    private static final String SESSION_ADMIN_KEY = "admin";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前Session，如果不存在则不创建新Session
        HttpSession session = request.getSession(false);
        System.out.println(1111+"admin拦截");
        if (session == null || session.getAttribute(SESSION_ADMIN_KEY) == null) {
            log.info("用户未登录或Session已过期");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 未授权
            response.sendRedirect("/a/AdminLogin");
            return false;
        }
        // 验证通过，放行请求
        log.debug("用户已登录，用户信息: {}", session.getAttribute(SESSION_ADMIN_KEY));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        // 可在此处添加请求完成后的处理逻辑
    }
}
